from flask import Blueprint,request,jsonify
import json
from db import db1

bp_auser = Blueprint('adminuser',__name__)

@bp_auser.route('/roleM',methods=['POST','GET'])
def roleM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select id from roles where name='%s'"%(data['name'])
        res = db1.find(sql)
        if res:
            return jsonify({'code':10011})
        else:
            sqlq = "insert into roles values(0,'%s')"%(data['name'])
            db1.update(sqlq)
            return jsonify({'code':200})
    else:
        sql = "select * from roles"
        res = db1.findall(sql)
        return({'code':200,'list':res})


@bp_auser.route('/resourcesM',methods=['POST'])
def resourcesM():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "insert into resources values(0,'%s','%s')"%(data['name'],data['url'])
    db1.update(sql)
    return jsonify({'code':200})


@bp_auser.route('/users',methods=['POST'])
def users():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "insert into admin_user values(0,'%s','%s',%d,%d)"%(data['name'],data['password'],int(data['is_admin']),int(data['role_id']))
    db1.update(sql)
    return jsonify({'code':200})